package com.go.where.manager.filter;

import java.io.IOException;
import java.util.Date;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.go.where.manager.common.Constants;
import com.go.where.manager.freemarker.CustomFreemarkerManager;
import com.go.where.manager.pojo.ActivityRetrospectInfo;
import com.go.where.manager.service.ActivityRetrospectService;
import com.go.where.manager.util.CommonUtil;

/**
 * 过滤URL地址
 * 
 * @author java
 * 
 */
public class URLFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httprequest = (HttpServletRequest) request;
		String requesturi = httprequest.getRequestURI();
		if (StringUtils.isNotBlank(requesturi)) {
			String[] uriArr = requesturi.split(CommonUtil.FILE_SEPARATOR);
			String fileName = null;
			String path = null;
			ApplicationContext APPLICATION_CONTEXT = WebApplicationContextUtils
					.getRequiredWebApplicationContext(httprequest.getSession()
							.getServletContext());
			if (uriArr != null && uriArr.length > 0) {
				fileName = uriArr[uriArr.length - 1];
				if (requesturi.contains("html") && !requesturi.contains("js")
						&& !requesturi.contains("css")) {
					String materialUrlPrefix = CustomFreemarkerManager
							.getValue("url.prefix");
					path = materialUrlPrefix + Constants.PROJECT_NAME
							+ CommonUtil.FILE_SEPARATOR
							+ Constants.MATERIAL_HTML + fileName;
					ActivityRetrospectService activityRetrospectService = (ActivityRetrospectService) APPLICATION_CONTEXT
							.getBean("activityRetrospectService");
					ActivityRetrospectInfo info = activityRetrospectService
							.queryByContent(path);
					if (info != null) {
						Integer browseNum = info.getBrowseNum();
						browseNum = CommonUtil.add(browseNum, 1);
						ActivityRetrospectInfo retro = new ActivityRetrospectInfo();
						retro.setRetroId(info.getRetroId());
						retro.setBrowseNum(browseNum);
						retro.setUpdateTime(new Date());
						activityRetrospectService.update(retro, null);
					}

				}
			}
		}

		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
